package com.heqiang.controller;


import com.heqiang.constant.Constant;
import com.heqiang.entity.manager.Admin;
import com.heqiang.service.AdminService;
import com.heqiang.tools.MD5;
import com.heqiang.utils.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/admin")
public class LoginController extends BaseController {

    @Autowired
    private AdminService service;

    /******************************************************* Go *******************************************************/
    //前往登录页
    @GetMapping(value = {"", "/", "/go/login", "/login"})
    public ModelAndView goLogin() {
        return goView("/admin/login");
    }

    //前往首页
    @RequestMapping("/go/index")
    public ModelAndView goIndex() {
        return goView("/admin/index");
    }

    //前往欢迎页面
    @RequestMapping("/go/welcome")
    public ModelAndView goWelcome() {
        return goView("/admin/welcome");
    }


    /******************************************************** Query ****************************************************/
    @RequestMapping("/login")
    public ModelAndView login(Admin admin, Model model, HttpServletRequest request, HttpServletResponse response) {
        Admin a = service.login(admin);
        String msg = "";
        if (null == a) {
            msg = "账号不存在!";
        } else {
            if (a.getPassword().equals(MD5.parseMD5(admin.getPassword() + Constant.PWD_SUFFIX))&&a.getStatus().equals(Admin.STATUS.OPEN)) {
                saveAdmin(request, a);
                return goView("redirect:/admin/go/index");
            }
            if (!a.getPassword().equals(MD5.parseMD5(admin.getPassword() + Constant.PWD_SUFFIX))) {
                msg = "密码错误";
            }
            if (a.getStatus().equals(Admin.STATUS.CLOSE)) {
                msg = "该账号已被禁用!";
            }
        }
        model.addAttribute("msg", msg);
        return goView("/admin/login");
    }

    /****************************************************************************************************************** Private *******************************************************************************************/
    //账号存入session
    public static void saveAdmin(HttpServletRequest request, Admin admin) {
        request.getSession().setAttribute(Constant.SESSION_KEY, admin);
    }
}
